package com.sduept.nwld.dataserver.manager.statistics;

import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.model.countanalyse.BreakerResponseTimeStatistics;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ResponseFeaBreakerManager {

	@Autowired
	private SuperDAO dao;
	
	public BreakerResponseTimeStatistics createOrUpdate(BreakerResponseTimeStatistics brts) {
		return dao.createOrUpdate(brts, BreakerResponseTimeStatistics.class);
	}
	
	public List<Integer> getAllYearsByVoltage(String voltage) {
		return (List<Integer>) dao.nativeQuery("select DISTINCT year from t_count_breaker_response_time_statistics where voltage_level='"+voltage+"' order by year desc");
	}
	
	public List<String> getAllVoltages() {
		return (List<String>) dao.nativeQuery("select DISTINCT voltage_level from t_count_breaker_response_time_statistics order by year desc");
	}
	
	public List<String> getAllAreas() {
		return (List<String>) dao.nativeQuery("select DISTINCT area from t_count_breaker_response_time_statistics order by area");
	}
	
	public List<BreakerResponseTimeStatistics> getAllBreakerResponseTimeStatistics() {
		return dao.findAll(BreakerResponseTimeStatistics.class);
	}
	
	public List<BreakerResponseTimeStatistics> queryByCondition(String year, String month, String area, String voltage) {
		return findByConditions(year, month, area, voltage);
	}
	
	/**
	 * 按条件查找
	 * @param year
	 * @param month
	 * @param area
	 * @param voltage
	 * @return
	 */
	private List<BreakerResponseTimeStatistics> findByConditions(String year, String month, String area,String voltage) {
		String sql = " 1=1 ";
		List<Object> values = new ArrayList<>();
		if (!StringUtils.isEmpty(year) && !year.contains("~")) {
			int y = Integer.parseInt(year);
			sql += " and year = ?  ";
			values.add(y);
		}
		if (!StringUtils.isEmpty(month) && !month.equals("all")) {
			int m = Integer.parseInt(month);
			sql += " and month = ?  ";
			values.add(m);
		}
		if (!StringUtils.isEmpty(area) && !area.equals("all")) {
			sql += "and area = ?  ";
			values.add(area);
		}
		
		if (!StringUtils.isEmpty(voltage) && !voltage.equals("all")) {
			sql += "and voltageLevel = ?  ";
			values.add(voltage);
		}
		sql += " order by year";
		List<BreakerResponseTimeStatistics> list = dao.findByCondition(BreakerResponseTimeStatistics.class, sql, values.toArray());
		return list;
	}
	
	public void deleteById(String id) {
		dao.delete(id, BreakerResponseTimeStatistics.class);
	}
}
